package com.zju.cst.cloudApp.command.impl;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import com.zju.cst.cloudApp.command.ActionHandler;
import com.zju.cst.cloudApp.command.CodeAnnotation;
import com.zju.cst.cloudApp.entity.Message;

public class BasicHandler implements ActionHandler {

	@Override
	public Message execute(Message message) {
		String code = message.getCode();
		String className = this.getClass().getName();
		Message msg = null;
		try {
			for (Method m : Class.forName(className).getMethods()) {
				if (m.getAnnotation(CodeAnnotation.class) != null) {
					if (code.equals(m.getAnnotation(CodeAnnotation.class).code())) {
						try {
							msg = (Message)m.invoke(this, message);
						} catch (IllegalArgumentException e) {
							e.printStackTrace();
						} catch (IllegalAccessException e) {
							e.printStackTrace();
						} catch (InvocationTargetException e) {
							e.printStackTrace();
						}
					}
				}
			}
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		return msg;
	}
}
